package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.eduSjtj01.*;
import com.jwsoft.manager.core.dao.mapper.EduSjtj01Mapper;
import com.jwsoft.manager.core.dao.model.EduSjtj01;
import com.jwsoft.manager.core.dao.model.EduStudentEnrollPre;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.EduSjtj01Integration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务统计查询业务实现类
 *
 * @author hhj
 * @since 2023-04-10
 */
@ApiService(funcCode = "sjtj01", title = "业务统计查询")
public class EduSjtj01IntegrationImpl implements EduSjtj01Integration {

    @Autowired
    public EduSjtj01Service eduSjtj01Service;
    @Autowired
    EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    EduHouseholdService eduHouseholdService;
    @Autowired
    EduHouseDetailService eduHouseDetailService;
    @Autowired
    EduSocialSecurityService eduSocialSecurityService;
    @Autowired
    EduLivePlaceService eduLivePlaceService;
    @Autowired
    EduHelper eduHelper;
    @Autowired
    CommonIntegration commonIntegration;
    @Autowired
    EduSjtj01Mapper mapper;
    @Autowired
    EduSystemConfigIntegration eduSystemConfigIntegration;

//    private final String getEnrolYbm = "task:addSjtj010004";

    @Override
    @OpApi(funcCode = "sjtj010001", title = "业务统计查询分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduSjtj01VO> getList(EduSjtj01QueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        List<EduSjtj01> list = eduSjtj01Service.list();
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSjtj01> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSjtj01VO> resultList = Convert.toList(EduSjtj01VO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "sjtj010002", title = "业务统计查询根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduSjtj01VO getById(EduSjtj01KeyVO vo) {
        EduSjtj01 entity = eduSjtj01Service.getById(vo.getEdusjtj01Id());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSjtj01VO result = Convert.convert(EduSjtj01VO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "sjtj010003", title = "业务统计查询保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSjtj01VO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "sjtj010004", title = "业务统计查询新增",
            funcType = FuncTypeEnum.insert,checkPrivilege = BoolEnum.FALSE,publicFlag =BoolEnum.TRUE)
    @SaveOplog(
            operationType = "sjtj010004",
            operationName = "业务统计查询新增",
            dataType = "edusjtj01Id",
            auType = AuTypeEnum.OTHER
    )
    public EduSjtj01InVO add(EduSjtj01InVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        //控制在业务期内
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setOperating("YW002");
        queryVO.setAreaCode(vo.getAreaCode());
        queryVO.setClassify("2");
        EduOperationCacheDetailVO bmOption=eduSystemConfigIntegration.getEduOperationOne(queryVO);
        if(bmOption!=null){
            if(bmOption.isFlag()){
                throw new AppException(bmOption.getYear()+"年度报名已开始");
            }else if(bmOption.getType().equalsIgnoreCase("2")){
                throw new AppException(bmOption.getYear()+"年度报名已结束");
            }
        }
        //删除已存在的
        LambdaQueryWrapper<EduSjtj01> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EduSjtj01::getYear, vo.getYear());
        lambdaQueryWrapper.eq(EduSjtj01::getAreaCode, vo.getAreaCode());
        if(eduSjtj01Service.count(lambdaQueryWrapper)>0){
            if (vo.getYear() < eduHelper.thisYear()) {
                throw new AppException("历史年度不能重新生成");
            }
            mapper.delete(lambdaQueryWrapper);
        }
        //按pre
        String aa = "";
        try {
            //hj
            aa="hj";
            eduSjtj01Service.insertEduSjtj01Hj(vo);

            System.out.println("hj");
            //fc
            aa="fc";
            eduSjtj01Service.insertEduSjtj01Fc(vo);
            eduSjtj01Service.insertEduSjtj01FcFather(vo);
            eduSjtj01Service.insertEduSjtj01FcMother(vo);
            aa = "wq";
            eduSjtj01Service.insertEduSjtj01Wq(vo);
            eduSjtj01Service.insertEduSjtj01WqFather(vo);
            eduSjtj01Service.insertEduSjtj01WqMother(vo);
            //cb
            aa="cb";
            eduSjtj01Service.insertEduSjtj01Cb(vo);
            eduSjtj01Service.insertEduSjtj01CbFather(vo);
            eduSjtj01Service.insertEduSjtj01CbMother(vo);

            //jz
            aa="jz";
            eduSjtj01Service.insertEduSjtj01Jz(vo);
            eduSjtj01Service.insertEduSjtj01JzFather(vo);
            eduSjtj01Service.insertEduSjtj01JzMother(vo);

        } catch (Exception e) {
            throw new AppException(aa+"执行失败!");
        }

        return vo;
    }

    @Override
    @OpApi(funcCode = "sjtj010005", title = "业务统计查询修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "sjtj010005",
            operationName = "业务统计查询修改",
            dataType = "edusjtj01Id",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSjtj01VO edit(EduSjtj01VO vo) {
        if (ObjectUtils.isEmpty(vo.getEdusjtj01Id())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSjtj01 oldEntity = eduSjtj01Service.getById(vo.getEdusjtj01Id());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSjtj01 entity = Convert.convert(EduSjtj01.class, vo);
        eduSjtj01Service.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "sjtj010006", title = "业务统计查询根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "sjtj010006",
            operationName = "业务统计查询删除",
            dataType = "edusjtj01Id",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSjtj01KeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getEdusjtj01Id())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSjtj01 entity = eduSjtj01Service.getById(vo.getEdusjtj01Id());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSjtj01Service.removeById(vo.getEdusjtj01Id());
    }

    @Override
    @OpApi(funcCode = "sjtj010007", title = "查询结果展示", funcType = FuncTypeEnum.insert,checkPrivilege = BoolEnum.FALSE,publicFlag =BoolEnum.TRUE)
    public EduSjtj01ResVO getResData(EduSjtj01InVO vo) {
        if(ObjectUtils.isEmpty(vo.getYear())){
            vo.setYear(eduHelper.thisYear());
        }
        if(ObjectUtils.isEmpty(vo.getAreaCode())){
            CommonVO commonVO=new CommonVO();
            commonVO.setParamKey("area_code");
            String areaCode=commonIntegration.getValueByKey(commonVO);
            vo.setAreaCode(areaCode);
        }
        EduSjtj01ResVO resvo = new EduSjtj01ResVO();
        resvo.setDjzrs(0L);
        resvo.setZrs(0);
        resvo.setZcbrs(0);
        resvo.setZfcrs(0);
        resvo.setZhjrs(0);
        resvo.setZjzzrs(0);

        resvo.setDjxxrs(0L);
        resvo.setXxrs(0);
        resvo.setXxcbrs(0);
        resvo.setXxfcrs(0);
        resvo.setXxhjrs(0);
        resvo.setXxjzrs(0);

        resvo.setDjzxrs(0L);
        resvo.setZxrs(0);
        resvo.setZxcbrs(0);
        resvo.setZxfcrs(0);
        resvo.setZxhjrs(0);
        resvo.setZxjzrs(0);

        QueryWrapper<EduSjtj01> qw = new QueryWrapper<>();
        qw.select("type,school_category ")
                .eq("year",vo.getYear())
                .eq("area_code",vo.getAreaCode());
        List<EduSjtj01> list= eduSjtj01Service.list(qw);
        if(!CollectionUtils.isEmpty(list)) {
            Map<String, Map<String, Long>> map = list.stream().filter(item ->
                    //做非空判断
                    StringUtil.isNotBlank(item.getType() + "") &&
                            StringUtil.isNotBlank(item.getSchoolCategory())
            ).collect(Collectors.groupingBy(EduSjtj01::getType, Collectors.groupingBy(EduSjtj01::getSchoolCategory, Collectors.counting())));
            for (String key : map.keySet()) {
                Map<String, Long> map1 = map.get(key);
                for (String key1 : map1.keySet()) {
                    int value = map1.get(key1).intValue();
                    resvo.setZrs(resvo.getZrs()+value);
                    if ("hj".equals(key)) {
                        resvo.setZhjrs(resvo.getZhjrs()+value);
                        if("2".equals(key1)){
                            resvo.setXxrs(resvo.getXxrs()+value);
                            resvo.setXxhjrs(resvo.getXxhjrs()+value);
                        }else {
                            resvo.setZxrs(resvo.getZxrs()+value);
                            resvo.setZxhjrs(resvo.getZxhjrs()+value);
                        }
                    } else if ("fc".equals(key)) {
                        resvo.setZfcrs(resvo.getZfcrs()+value);
                        if("2".equals(key1)){
                            resvo.setXxrs(resvo.getXxrs()+value);
                            resvo.setXxfcrs(resvo.getXxfcrs()+value);
                        }else {
                            resvo.setZxrs(resvo.getZxrs()+value);
                            resvo.setZxfcrs(resvo.getZxfcrs()+value);
                        }
                    } else if ("cb".equals(key)) {
                        resvo.setZcbrs(resvo.getZcbrs()+value);
                        if("2".equals(key1)){
                            resvo.setXxrs(resvo.getXxrs()+value);
                            resvo.setXxcbrs(resvo.getXxcbrs()+value);
                        }else {
                            resvo.setZxrs(resvo.getZxrs()+value);
                            resvo.setZxcbrs(resvo.getZxcbrs()+value);
                        }
                    } else if ("jz".equals(key)) {
                        resvo.setZjzzrs(resvo.getZjzzrs()+value);
                        if("2".equals(key1)){
                            resvo.setXxrs(resvo.getXxrs()+value);
                            resvo.setXxjzrs(resvo.getXxjzrs()+value);
                        }else {
                            resvo.setZxrs(resvo.getZxrs()+value);
                            resvo.setZxjzrs(resvo.getZxjzrs()+value);
                        }
                    }
                }
            }
        }

        QueryWrapper<EduStudentEnrollPre> zrsquery=new QueryWrapper<>();
        zrsquery.lambda().eq(EduStudentEnrollPre::getYear,vo.getYear())
                .eq(StringUtil.isNotBlank(vo.getAreaCode()),EduStudentEnrollPre::getAreaCode,vo.getAreaCode());
        resvo.setDjzrs(eduStudentEnrollPreService.count(zrsquery));
        QueryWrapper<EduStudentEnrollPre> xxzrsquery=new QueryWrapper<>();
        xxzrsquery.lambda().eq(EduStudentEnrollPre::getYear,vo.getYear())
                .eq(EduStudentEnrollPre::getSchoolCategory, SchoolCategoryEnum.PRIMARY.getType())
                .eq(StringUtil.isNotBlank(vo.getAreaCode()),EduStudentEnrollPre::getAreaCode,vo.getAreaCode());
        resvo.setDjxxrs(eduStudentEnrollPreService.count(xxzrsquery));
        QueryWrapper<EduStudentEnrollPre> czzrsquery=new QueryWrapper<>();
        czzrsquery.lambda().eq(EduStudentEnrollPre::getYear,vo.getYear())
                .eq(EduStudentEnrollPre::getSchoolCategory, SchoolCategoryEnum.JUNIOR.getType())
                .eq(StringUtil.isNotBlank(vo.getAreaCode()),EduStudentEnrollPre::getAreaCode,vo.getAreaCode());
        resvo.setDjzxrs(eduStudentEnrollPreService.count(czzrsquery));
        return resvo;
    }

}
